﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SmallShop.BaseWeb;
using SmallShop.Bll;
using SmallShop.Core.Enums;
using SmalShop.Model;
using SmallShop.Frame;

namespace SmallShop.ManagerWeb.Controllers
{
    public class ProductController : SmallController
    {
        private readonly ProductBiz _productBiz;
        public ProductController()
        {
            _productBiz = new ProductBiz();
        }

        // GET: Product
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="title"></param>
        /// <param name="status"></param>
        /// <param name="cateId"></param>
        /// <param name="page">页码</param>
        /// <param name="limit">页长</param>
        /// <returns></returns>
        public ActionResult List(string title = "", int status = 0, int cateId = 0, int page = 1, int limit = 10)
        {
            var query = _productBiz.Query();
            if (!string.IsNullOrEmpty(title))
            {
                query = query.Where(it => it.Title.Contains(title));
            }
            
            if (status > 0 && Enum.IsDefined(typeof(ProductStatus), status))
            {
                var pStatus =(ProductStatus) status;
                query = query.Where(it => it.Status == pStatus);
            }

            if (cateId > 0)
            {
                query = query.Where(it => it.CateId == cateId);
            }
            
            var count = query.Count();
            var rows = query.OrderByDescending(it=>it.Id).Skip((page-1) * limit).Take(limit).ToList();
            return Json(new ResultModel
            {
                Data = new {rows, count}
            });
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Add(ProductModel model)
        {
            return Json(_productBiz.Add(model));
        }
        
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Update(ProductModel model)
        {
            return Json(_productBiz.Update(model));
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(long id)
        {
            return Json(_productBiz.Delete(id));
        }
    }
}